package com.smartwebx.fr.util;

import java.util.ArrayList;
import java.util.List;

import com.aspose.words.IReplacingCallback;
import com.aspose.words.Node;
import com.aspose.words.NodeType;
import com.aspose.words.ReplaceAction;
import com.aspose.words.ReplacingArgs;
import com.aspose.words.Run;
import com.google.common.collect.Lists;

public class FindMatchedNodes implements IReplacingCallback {
	public List<Run> nodes = Lists.newArrayList();

	@Override
	public int replacing(ReplacingArgs e) throws Exception {
		Node currentNode = e.getMatchNode();

		if (e.getMatchOffset() > 0) {
			currentNode = splitRun((Run) currentNode, e.getMatchOffset());
		}
		ArrayList runs = new ArrayList();
		int remainingLength = e.getMatch().group().length();
		while ((remainingLength > 0) && (currentNode != null) && (currentNode.getText().length() <= remainingLength)) {
			runs.add(currentNode);
			remainingLength = remainingLength - currentNode.getText().length();
			do {
				currentNode = currentNode.getNextSibling();
			} while ((currentNode != null) && (currentNode.getNodeType() != NodeType.RUN));
		}

		if ((currentNode != null) && (remainingLength > 0)) {
			splitRun((Run) currentNode, remainingLength);
			runs.add(currentNode);
		}

		String runText = "";
		for (Object run : runs) {
			String text = ((Run) run).getText();
			runText += text;
		}

		((Run) runs.get(0)).setText(runText);

		for (int i = 1; i < runs.size(); i++) {
			((Run) runs.get(i)).remove();
		}

		nodes.add((Run) runs.get(0));
		return ReplaceAction.SKIP;
	}

	/**
	 * Splits text of the specified run into two runs. Inserts the new run just
	 * after the specified run.
	 */
	private static Run splitRun(Run run, int position) throws Exception {
		Run afterRun = (Run) run.deepClone(true);
		afterRun.setText(run.getText().substring(position));
		run.setText(run.getText().substring((0), (0) + (position)));
		run.getParentNode().insertAfter(afterRun, run);
		return afterRun;
	}
}
